k8s中的dns从skyDNS到kubeDns,再到今天的coreDNS,目的很简单,那就是为了让集群中的应用通过service和namespace来找到对应的服务,以组建更稳定更高效的应用集群;但coreDNS的能力应该远非与此,那可以还做什么呢?生产过程中,某些服务在某些场景下是需要配置域名来访问的,但因为集群很多时候是内网集群,网络可能会限制内网服务器访问外网,就算能访问外网,你访问内网服务还要走公网走一圈再回到内网,这样对内网网关的压力,以及·网络延迟增高都有很大影响,所以你需要个内网dns,让这些内网服务直接走内网解析,这篇文章会大概讲下利用k8s集群自带的coreDNS搭建一个内网dns
- 我们先来看下coredns的在k8a中的各个资源
Pod(
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804112835.png)
- Service(```kube-dns```)
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804113110.png)
- ConfigMap(```coredns```)
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804162604.png)
> coredns是模块化功能,默认只解析k8s中的集群,和把集群解析不到的转达到node的/etc/resolv.conf去解析,我们想实现上面想法,还是要修改coredns的配置文件去完成,也就是k8s中对应的configmap
2. 实现自定义服务解析
- 查看coredns默认configmap
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804163515.png)
> error: 错误记录到stdout
> health:CoreDNS的运行状况报告为http:// localhost:8080 / health
> kubernetes:CoreDNS将根据Kubernetes服务和pod的IP回复DNS查询
> prometheus:CoreDNS的度量标准可以在http://localhost:9090/Prometheus格式的指标中找到
> forward :任何不在Kubernetes集群域内的查询都将转发到预定义的解析器(/etc/resolv.conf)
> cache:启用前端缓存
> loop:检测简单的转发循环,如果找到循环则停止CoreDNS进程
> reload:允许自动重新加载已更改的Corefile。编辑ConfigMap配置后,请等待两分钟以使更改生效
> loadbalance:这是一个循环DNS负载均衡器,可以在答案中随机化A,AAAA和MX记录的顺序
- 添加host模块到默认域解析域名到对应主机
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804164024.png)
> hosts 中做主机解析,可以一个域名对应多个主机
- 在pod中测试解析
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804165313.png)
> 可以看到都可以解析成功,当然我们也可以这样配置↓↓
- 另一种配置方式
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804170921.png)
> 新建chulinx.com域,在新建的域中做hosts,这种方法其实和上面👆类型
- 再次测试
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804165313.png)
> 我们上面说了,要实现所有节点对自定义服务的域名解析,所以所有节点的域名解析文件resolv.conf中应该这么写```nameserver 10.96.0.10```,那原来k8s集群解析外网的```forward . /etc/resolv.conf ``` 会使解析回流到自己,就会出现解析错误,说了这么多,其实我们只是需要一个dns的递归查询
3. coreDNS实现递归查询
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804171945.png)
> 其实就是把```forward . /etc/resolv.conf ```换成```proxy . 114.114.114.114```,这样如果coredns遇到查询不到的域名就会转发给114去查询,再返回给pod或者node
4. 在node上配置coredns 实现node解析k8s service、自定义域名解析,外网域名解析
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804172834.png)
5. 其他内网主机配置coredns解析
- 修改kube-dns service,主要修改service Type 为NodePort,修改udp 53 nodePort为53
![](https://raw.githubusercontent.com/chulinx/imgs/master/20190804174049.png)
- 修改其他主机resolv.conf 为k8s集群节点ip ```nameserver 172.16.1.198测试
最后用ansible推下resolv.conf到所有服务器,至此,内网全方位dns方案就完美做完,这套方案,既包含了dns的高可用,又兼顾自定义域名和dns的递归查询
- 本文作者: ChuLinx
- 本文链接: http://yoursite.com/2019/11/30/Kubernetes 实现全方位集群内私有dns/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!